// Pinia Token持久化测试工具
import { useUserStore } from '@/stores/user'

// 测试Pinia持久化功能
export const testPiniaPersistence = () => {
  console.log('🧪 开始测试Pinia持久化功能...')
  
  const userStore = useUserStore()
  
  // 清除当前状态
  userStore.clearUser()
  console.log('1️⃣ 清除用户状态')
  
  // 模拟用户数据
  const mockUser = {
    id: 1,
    uuid: 'test-uuid-123',
    username: 'piniatest',
    email: 'pinia@test.com',
    subscriptionType: 'free'
  }
  
  // 模拟登录，设置24小时过期
  const testToken = 'pinia-test-token-' + Date.now()
  userStore.login(testToken, mockUser, 24)
  
  console.log('2️⃣ 模拟登录完成')
  console.log('  用户:', userStore.user?.username)
  console.log('  Token:', userStore.token?.substring(0, 20) + '...')
  console.log('  认证状态:', userStore.isAuthenticated)
  console.log('  剩余时间:', userStore.getTokenRemainingTime(), '分钟')
  
  // 检查localStorage
  const persistedData = localStorage.getItem('user-store')
  console.log('3️⃣ localStorage数据:', persistedData ? '已保存' : '未保存')
  
  if (persistedData) {
    try {
      const parsed = JSON.parse(persistedData)
      console.log('  用户数据:', parsed.user?.username)
      console.log('  Token数据存在:', !!parsed.tokenData)
      console.log('  过期时间:', new Date(parsed.tokenData?.expiresAt).toLocaleString())
    } catch (e) {
      console.error('  解析失败:', e)
    }
  }
  
  console.log('✅ Pinia持久化测试完成！')
  console.log('💡 现在可以刷新页面测试状态恢复')
}

// 检查页面加载时的状态恢复
export const checkStateRestoration = () => {
  console.log('🔍 检查状态恢复...')
  
  const userStore = useUserStore()
  
  console.log('📊 当前状态:')
  console.log('  认证状态:', userStore.isAuthenticated)
  console.log('  用户:', userStore.user?.username || '未登录')
  console.log('  Token存在:', !!userStore.token)
  
  if (userStore.tokenData) {
    const remaining = userStore.getTokenRemainingTime()
    console.log('  剩余时间:', remaining, '分钟')
    console.log('  即将过期:', userStore.isTokenExpiringSoon())
  }
  
  const persistedData = localStorage.getItem('user-store')
  console.log('📦 localStorage状态:', persistedData ? '存在' : '不存在')
  
  if (userStore.isAuthenticated) {
    console.log('✅ 状态恢复成功！')
  } else {
    console.log('❌ 状态未恢复（可能是首次访问或token已过期）')
  }
}

// 暴露到全局
if (typeof window !== 'undefined') {
  ;(window as any).testPiniaPersistence = testPiniaPersistence
  ;(window as any).checkStateRestoration = checkStateRestoration
  
  console.log('🛠️ Pinia持久化测试工具已加载！')
  console.log('  testPiniaPersistence() - 测试持久化功能')
  console.log('  checkStateRestoration() - 检查状态恢复')
  
  // 自动检查状态恢复
  setTimeout(() => {
    checkStateRestoration()
  }, 100)
}
